/*
 * Copyright 2006 Matt Jensen
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
package org.jtell.xdoclet;

import xjavadoc.XMethod;
import xjavadoc.Type;
import xjavadoc.XClass;
import xjavadoc.XParameter;
import org.jtell.internal.ReflectionUtils;

import java.util.List;
import java.lang.reflect.Method;

/**
 * <p>
 * <code>XJavaDocUtils</code> provides utility methods for dealing with XJavadoc elements.
 * </p>
 */
public class XJavaDocUtils
{
    /**
     * <p>
     * Construct a {@link XJavaDocUtils} instance.
     * </p>
     */
    private XJavaDocUtils()
    {
        super();
    }

    /**
     * <p>
     * Get the signature of an xjavadoc method. Follows the same rules as
     * {@link ReflectionUtils#getMethodSignature(Method)}.
     * </p>
     *
     * @param method the method.
     * @return {@link String} method signature.
     */
    public static String getMethodSignature(final XMethod method)
    {
        // Add the method name.
        final StringBuilder resultBuilder = new StringBuilder();
        appendTypeName(resultBuilder, method.getReturnType());
        resultBuilder.append(' ');
        resultBuilder.append(method.getName());
        resultBuilder.append('(');

        // Add the fully-qualified parameter types.
        @SuppressWarnings("unchecked")
        final List<XParameter> parameters = method.getParameters();
        boolean first = true;
        for (final XParameter parameter : parameters)
        {
            if (first)
            {
                first = false;
            }
            else
            {
                resultBuilder.append(',');
            }
            appendTypeName(resultBuilder, parameter);
        }
        resultBuilder.append(')');
        return resultBuilder.toString();
    }

    /**
     * <p>
     * Get the name of an xjavadoc type.
     * </p>
     *
     * @param outputBuilder the string builder to which the type name will be written.
     * @param type the type.
     */
    public static void appendTypeName(final StringBuilder outputBuilder, final Type type)
    {
        final XClass clazz = type.getType();
        outputBuilder.append(clazz.getQualifiedName());
        final int dimension = type.getDimension();
        for (int i = 0; i < dimension; ++i)
        {
            outputBuilder.append("[]");
        }
    }
}
